#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'YC'

import os
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib.path as path

def createplot(data,minnum,maxnum,rngname,timeused):
    # histogram our data with numpy
    fig, ax = plt.subplots()
    #data = np.random.randn(1000)
    #data = [1,3,45,76,23,76,23,76,32,87,321,65]
    binnum = maxnum-minnum+1
    #n, bins = np.histogram(data, bins=binnum,density=False)
    #print(n)
    n, bins = np.histogram(data, bins=binnum,density=True)                
    n = n*np.diff(bins)
    
    # get the corners of the rectangles for the histogram
    '''
    left = np.array(bins[:-1])
    right = np.array(bins[1:])
    bottom = np.zeros(len(left))
    top = bottom + n

    # we need a (numrects x numsides x 2) numpy array for the path helper
    # function to build a compound path
    XY = np.array([[left,left,right,right], [bottom,top,top,bottom]]).T

    # get the Path object
    barpath = path.Path.make_compound_path_from_polys(XY)

    # make a patch out of it
    patch = patches.PathPatch(barpath, facecolor='green', edgecolor='white', alpha=1.0)
    ax.add_patch(patch)

    # update the view limits
    ax.set_xlim(left[0], right[-1])
    ax.set_ylim(bottom.min(), top.max())
    plt.xlabel('Random Number Section')
    plt.ylabel('Probability')
    plt.title('Histogram of RNG')
    

    #print("sum probabiliy is :",n.sum()," " ,np.sum(n*np.diff(bins)))

    filename = os.getcwd()+"/histogram"+"_"+str(rngname)+".png"
    print("saving file to "+filename)
    plt.savefig(filename)
    '''
    #only saving statistical data
    retfilename = os.getcwd()+ "/result_"+str(rngname)+".txt"
    if os.path.isfile(retfilename):
        retFile = open(retfilename,"a")
    else:
        retFile = open(retfilename,"w")
        retFile.write("Cariance\tTimeUsed(ns)\n")
    
    expectation,cariance = computeCariance(n)
    retFile.write("%f\t%u\n" % (cariance,timeused))
    retFile.close()
    
    #plt.show()

def computeCariance(data):
    numbers = len(data)
    #print("sum data:",sum(data))
    expectation = sum(data)/numbers
    data = [i-expectation for i in data]
    newdata = [pow(i,2) for i in data]
    return expectation,sum(newdata)/numbers

def createplot1(data):
    '''
         得到的是概率统计
    '''
    weights = np.ones_like(data)/len(data)
    n,bins,patches=plt.hist(data,3,weights=weights,normed=True,color='g',alpha=1.0)
    
    #left = np.array(bins[:-1])
    #right = np.array(bins[1:])
    
    plt.xlabel('Random Number Section')
    plt.ylabel('Probability')
    plt.title('Histogram of RNG')
    plt.axis([0, 4,0,1.0])
    #print("saving file to "+os.getcwd()+"/histogram1.png")
    #plt.savefig(os.getcwd()+"/histogram1.png")
    #plt.grid(True)
    plt.show()

if __name__ == "__main__":
    createplot([0,1,2,3,4],"test")

